//
//  MTScrollHidePopViewController.swift
//  PPKit
//
//  Created by iosdevmac201 on 2020/9/15.
//  Copyright © 2020 scoresdata.net. All rights reserved.

import UIKit

/**
*
///懒加载
lazy var popupController:MTScrollHidePopViewController = {
    //aview也可以去懒加载
    let contentView = UIView()
    let popupController = MTScrollHidePopViewController(conView: aview)
    return popupController
}()

///弹出
if popupController.view.superview == nil, let naviCtl = self.navigationController {
    popupController.showInMatchPopupScreen(controller: naviCtl)
}
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
 
///提供一个高度变化的方法，当内容高度变化之后，需要重新布局
func updateContentView()
aview.frameBlock = {[weak self] (new_height) in
 popupController.containerView.height = new_height
 popupController.updateContentView()
}
*
*/

class MTScrollHidePopViewController: XPBaseViewController {
    
    var containerView:UIView!
    ///当前正在拖拽的是否是tableView
    private var isDragScrollView = false
    ///向下拖拽最后时刻的位移
    private var lastDrapDistance:CGFloat = 0
    ///当前的长按手势
    private var panGestureRecognizer:UIPanGestureRecognizer?
    
    private var scrollView:UIScrollView?
    
    private lazy var maskControl:UIControl = {
        let maskControl = UIControl()
        maskControl.backgroundColor = pp_color("000000", "000000").withAlphaComponent(0.4)
        maskControl.addTarget(self, action: #selector(maskControlEvent), for: .touchUpInside)
        return maskControl
    }()
    
    
    //MARK: 默认基类方法
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .default
    }
    
    init(conView:UIView) {
        super.init(nibName: nil, bundle: nil)
        containerView = conView
        initNavigationBar()
        initSubViews()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        containerView.corner(byRoundingCorners: [.topLeft, .topRight], radii: 8.scale)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    /// 初始化导航栏
    override func initNavigationBar() {
        super.initNavigationBar()
        hideNavigationBar()
    }
    
    /// 初始化页面子控件视图
    override func initSubViews() {
        super.initSubViews()
        view.backgroundColor = .clear
        maskControl.beAddInto(view).snp.makeConstraints { m in
            m.edges.equalToSuperview()
        }
        let pan = UIPanGestureRecognizer(target: self, action: #selector(pan(panGestureRecognizer:)))
        pan.delegate = self
        containerView.addGestureRecognizer(pan)
        self.panGestureRecognizer = pan
        view.addSubview(containerView)
        containerView.frame = CGRect(x: 0, y: pp_screen_height, width: containerView.width, height: containerView.height)
    }
    
    /// 显示
    func showInMatchPopupScreen(controller:UIViewController) {
        view.frame = controller.view.bounds
        controller.addChild(self)
        controller.view.addSubview(view)
        view.layoutIfNeeded()
        beginAppearanceTransition(true, animated: true)
        maskControl.alpha = 0
        containerView.frame = CGRect( x: 0, y: pp_screen_height, width: containerView.width, height: containerView.height)
        UIView.animate(withDuration: 0.25, animations: {
            self.containerView.layer.transform = CATransform3DMakeTranslation(0, -self.containerView.height, 0)
            self.maskControl.alpha = 1
        }) { (finushed) in
            self.didMove(toParent: self)
            self.endAppearanceTransition()
        }
    }
    
    /// 隐藏
    func hide() {
        self.beginAppearanceTransition(false, animated: true)
        UIView.animate(withDuration: 0.25, animations: {
            self.containerView.layer.transform = CATransform3DIdentity
            self.maskControl.alpha = 0
        }) { (finished) in
            self.removeFromParent()
            self.endAppearanceTransition()
            self.view.removeFromSuperview()
        }
    }
    
    /// 当contentView高度改变是，你需要重新布局
    func updateContentView() {
        self.containerView.layer.transform = CATransform3DMakeTranslation(0, -self.containerView.height, 0)
    }
    
    /// 背景蒙层点击，取消按钮点击
    @objc func maskControlEvent() {
        hide()
    }
}

//MARK: #委托代理#
extension MTScrollHidePopViewController:UIGestureRecognizerDelegate{
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if gestureRecognizer == panGestureRecognizer {
            var touchView = touch.view
            while touchView != nil {
                if let newTouchView = touchView as? UIScrollView {
                    isDragScrollView = true
                    self.scrollView = newTouchView
                    break
                } else if touchView == containerView {
                    isDragScrollView = false
                    break
                }
                touchView = touchView?.next as? UIView
            }
        }
        return true
    }
    
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if gestureRecognizer is UITapGestureRecognizer {
            //如果是点击手势
            let point = gestureRecognizer.location(in: containerView)
            if containerView.layer.contains(point) && gestureRecognizer.view == self {
                return false
            }
        }else if gestureRecognizer == panGestureRecognizer {
            //如果是自己加的拖拽手势
            print("gestureRecognizerShouldBegin")
        }
        return true
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        if gestureRecognizer == panGestureRecognizer {
            if (otherGestureRecognizer == scrollView?.panGestureRecognizer) || (otherGestureRecognizer is UIPanGestureRecognizer) {
                if otherGestureRecognizer.view is UIScrollView {
                    return true
                }
            }
        }
        return false
    }
    
    @objc func pan(panGestureRecognizer: UIPanGestureRecognizer) {
        // 获取手指的偏移量
        let transP = panGestureRecognizer.translation(in: containerView)
        if isDragScrollView {
            if (scrollView?.contentOffset.y ?? 0) <= 0 {
                //如果tableView置于顶端
                if transP.y > 0 {
                    //如果向下拖拽
                    scrollView?.contentOffset = CGPoint(x: 0, y: 0)
                    scrollView?.panGestureRecognizer.isEnabled = false
                    scrollView?.panGestureRecognizer.isEnabled = true
                    isDragScrollView = false
                    //向下拖
                    containerView.frame = CGRect(x: containerView.frame.origin.x, y: containerView.frame.origin.y + transP.y, width: containerView.frame.size.width, height: containerView.frame.size.height)
                } else {
                    //如果向上拖拽
                }
            }
        }else{
            if transP.y > 0 {
                //向下拖
                containerView.frame = CGRect(x: containerView.frame.origin.x, y: containerView.frame.origin.y + transP.y, width: containerView.frame.size.width, height: containerView.frame.size.height)
            } else if transP.y < 0 && containerView.frame.origin.y > (pp_screen_height - containerView.frame.size.height) {
                //向上拖
                containerView.frame = CGRect(x: containerView.frame.origin.x, y: (containerView.frame.origin.y + transP.y) > (pp_screen_height - containerView.frame.size.height) ? (containerView.frame.origin.y + transP.y) : (pp_screen_height - containerView.frame.size.height), width: containerView.frame.size.width, height: containerView.frame.size.height)
            } else {
                
            }
        }
        
        panGestureRecognizer.setTranslation(CGPoint.zero, in: containerView)
        if panGestureRecognizer.state == .ended {
            if lastDrapDistance > 10 && isDragScrollView == false {
                //如果是类似轻扫的那种
                hide()
            }else{
                if containerView.frame.origin.y >= pp_screen_height - containerView.frame.size.height / 2 {
                    hide()
                }else{
                    UIView.animate(withDuration: 0.25,delay: 0.0, options: .curveEaseOut, animations: { [self] in
                        var frame = self.containerView.frame
                        frame.origin.y = pp_screen_height - self.containerView.frame.size.height
                        self.containerView.frame = frame
                    }) { finished in
                        print("结束")
                    }
                }
            }
        }
        lastDrapDistance = transP.y
    }
}
